package main

import "io/ioutil"
import "strings"
import "path"
import "fmt"

/*
    Calculate the desired classpath. 
    
    Entries are specified by xj.path*=* in the designated
    directory. Entries are taken from files named by
    xj.path* in ditto. Entries starting @ are filenames
    containing more entries or directories to inspect
    for xj.path names.
*/

func main() {
    investigate( make(stringSet), "." )
}

type stringSet map[string]bool

func investigate(seen stringSet, dirName string) {
    infos, err := ioutil.ReadDir( dirName )
    if err == nil {
        for _, fi := range infos {
            name := fi.Name
            if strings.HasPrefix( name, "xj.path" ) {
                eq := strings.Index( name, "=" )
                if eq < 0 {
                    investigateFile(seen, name)
                } else {
                    addFileEntry(seen, name[eq+1:])
                }
            }        
        }
    }
}

func investigateFile(seen stringSet, fileName string) {
    fmt.Printf( ">> investigating file %v\n", fileName )
    if seen[fileName] { return }
    seen[fileName] = true
    bytes, err := ioutil.ReadFile( fileName )
    if err == nil {
        s := strings.Split( string(bytes), "\n", 0 )
        for _, line := range s {
            if len(line) > 0 { 
                fmt.Printf( ">>   it contains a line %v\n", line )
                if line[0] == '@' {
                    investigateFile(seen, resolve(fileName, line[1:]))
                } else {
                    addFileEntry(seen, resolve(fileName, line))
                }
            }
        }
    }
}

func resolve(baseName string, fileName string ) string {
    if fileName[0] == '/' { return fileName }
    return path.Clean( path.Join( baseName, fileName ) )
}

func addFileEntry(seen stringSet, fileName string) {
    fmt.Printf( "ENTRY: %v\n", fileName )
}






